import requests
import json

# Flask 应用运行的地址
BASE_URL = 'http://127.0.0.1:5000'

# 注册一个新用户
def register_user(username, password):
    url = f'{BASE_URL}/register'
    data = {
        'username': username,
        'password': password
    }
    response = requests.post(url, json=data)
    return response.status_code, response.json()

# 用户登录
def login_user(username, password):
    url = f'{BASE_URL}/login'
    data = {
        'username': username,
        'password': password
    }
    response = requests.post(url, json=data)
    return response.status_code, response.json()

# 查询数据
def re_data():
    url = f'{BASE_URL}/sensor_datas'
    data = {
        'sensors': "temp",
        'sensor_num': '10'
    }
    response = requests.post(url, json=data)
    return response.status_code, response.json()
# 测试注册和登录功能
def registration_and_login():
    # 注册用户
    reg_status, reg_response = register_user('admin', 'admin')
    print(f'Registration Status: {reg_status}, Response: {json.dumps(reg_response, indent=2)}')
    
    if reg_status == 201:  # 用户注册成功
        # 尝试登录
        login_status, login_response = login_user('admin', 'admin')
        print(f'Login Status: {login_status}, Response: {json.dumps(login_response, indent=2)}')
        
        if login_status == 200:  # 登录成功
            print('用户能够注册和登录')
        else:
            print('用户注册后无法登录')
    else:
        print('用户注册失败')


# 运行测试
code, jsona =re_data()
print(code, jsona)